<template>
  <div class="user-management">
    <SimpleSidebar />
    <div class="content-wrapper">
      <el-card class="header-card" shadow="hover">
        <div class="header-content">
          <h1>推流信息管理</h1>
          <el-button type="primary" @click="handleAdd" icon="Plus" class="add-btn">
            添加信息
          </el-button>
        </div>
      </el-card>

      <el-card class="user-list" shadow="never">
        <el-table :data="user" style="width: 100%" stripe border :header-cell-style="{background: '#f5f7fa', color: '#606266'}" v-loading="loading">
          <el-table-column prop="id" label="ID" width="240" sortable align="center" />
          <el-table-column prop="vid" label="视频ID" width="240" align="center" />
          <el-table-column prop="views" label="观看次数" width="240" align="center">
            <template #default="scope">
              <el-tag :type="getViewsTagType(scope.row.views)">
                {{ scope.row.views }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280" align="center" fixed="right">
            <template #default="scope">
              <el-button size="small" @click="handleEdit(scope.row)" icon="Edit" class="edit-btn">
                编辑
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(scope.row)" icon="Delete" class="delete-btn">
                删除
              </el-button>
              <el-button 
                size="small" 
                type="primary" 
                @click="$router.push(`/display-chart/${scope.row.id}`)" 
                icon="Right" 
                plain
              >
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-wrapper">
          <el-pagination
              background
              layout="total, sizes, prev, pager, next, jumper"
              :page-sizes="[10, 20, 50, 100]"
              :total="total"
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="500px"
        :close-on-click-modal="false"
        custom-class="custom-dialog"
    >
      <el-form
          :model="currentUser"
          label-width="100px"
          label-position="left"
          :rules="rules"
          ref="formRef"
      >
        <el-form-item label="ID" prop="id">
          <el-input v-model="currentUser.id" placeholder="请输入ID" />
        </el-form-item>
        <el-form-item label="视频ID" prop="vid">
          <el-input v-model="currentUser.vid" placeholder="请输入视频ID" />
        </el-form-item>
        <el-form-item label="观看次数" prop="views">
          <el-input-number
              v-model="currentUser.views"
              :min="0"
              :max="999999"
              controls-position="right"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import SimpleSidebar from './SimpleSidebar.vue'
import { ElMessage, ElMessageBox } from "element-plus"
import axios from 'axios'

// 用户数据
const user = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const formRef = ref(null)

// 对话框控制
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)

// 当前操作的用户
const currentUser = ref({
  id: '',
  vid: '',
  views: 0
})

// 表单验证规则
const rules = {
  id: [{ required: true, message: '请输入ID', trigger: 'blur' }],
  vid: [{ required: true, message: '请输入视频ID', trigger: 'blur' }],
  views: [{ required: true, message: '请输入观看次数', trigger: 'blur' }]
}

// 根据观看次数获取标签类型
const getViewsTagType = (views) => {
  if (views > 100) return 'success'
  if (views > 50) return 'primary'
  if (views > 10) return 'warning'
  return 'danger'
}

// 添加用户
const handleAdd = () => {
  dialogTitle.value = '添加用户'
  isEdit.value = false
  currentUser.value = {
    id: '',
    vid: '',
    views: 0
  }
  dialogVisible.value = true
}

// 编辑用户
const handleEdit = (user) => {
  dialogTitle.value = '编辑用户'
  isEdit.value = true
  currentUser.value = JSON.parse(JSON.stringify(user))
  dialogVisible.value = true
}

// 删除用户
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该用户信息吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      customClass: 'delete-message-box'
    })

    // 调用删除接口
    const response = await axios.post('/videoRank/deleteVideoRankById', null, {
      params: { id: row.id },
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
    })
   

    if (response.data && response.data.code === 200) {
      user.value = user.value.filter(s => s.id !== row.id)
      ElMessage.success('删除成功！')
      fetchUsers() // 重新加载数据确保同步
    } else {
      throw new Error(response.data.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error(error.message || '删除失败')
    } else {
      ElMessage.info('已取消删除')
    }
  }
}

// 确认添加/编辑
const handleConfirm = async () => {
  try {
    const valid = await formRef.value.validate()
    if (!valid) return

    if (isEdit.value) {
      // 调用更新接口
      const response = await axios.post('/videoRank/updateVideoRankById', null, {
        params: currentUser.value,
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
      })

      if (response.data && response.data.code === 200) {
        const index = user.value.findIndex(s => s.id === currentUser.value.id)
        if (index !== -1) {
          user.value[index] = currentUser.value
        }
        ElMessage.success('修改成功！')
        fetchUsers() // 重新加载数据确保同步
      } else {
        throw new Error(response.data.message || '更新失败')
      }
    } else {
      // 调用添加接口
      const response = await axios.post('/videoRank/add', null, {
        params: currentUser.value,
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
      })

      if (response.data && response.data.code === 200) {
        user.value.push(currentUser.value)
        ElMessage.success('添加成功！')
        fetchUsers() // 重新加载数据确保同步
      } else {
        throw new Error(response.data.message || '添加失败')
      }
    }

    dialogVisible.value = false
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error(error.message || '操作失败')
  }
}

// 每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchUsers()
}

// 页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchUsers()
}

// API调用函数
const fetchUsers = async () => {
  loading.value = true
  try {
    const response = await axios.post('/videoRank/loadDataList', null, {
      params: {
        pageNo: currentPage.value,
        pageSize: pageSize.value
      },
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })

    let resultData = []
    if (response.data && typeof response.data === 'object') {
      if (Array.isArray(response.data.data.list)) {
        resultData = response.data.data.list
      }
      if (response.data.data.totalCount !== undefined) {
        total.value = response.data.data.totalCount
      }
    }

    user.value = resultData
  } catch (error) {
    console.error('请求失败:', error)
    ElMessage.error(error.message || '获取数据失败')
  } finally {
    loading.value = false
  }
}

// 组件挂载时加载数据
onMounted(fetchUsers)
</script>

<style scoped>
.user-management {
  display: flex;
  min-height: 100vh;
  background: linear-gradient(135deg, #b6e0ff 0%, #f7d9ff 100%);
}

.content-wrapper {
  flex: 1;
  padding: 20px;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.8) 0%, rgba(240, 248, 255, 0.8) 100%);
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  margin-left: 220px;
}

.header-card {
  margin-bottom: 20px;
  border-radius: 12px;
  border: none;
  background: linear-gradient(135deg, #d9efff 0%, #f7d9ff 100%);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
}

.header-card h1 {
  margin: 0;
  color: #495057;
  font-size: 22px;
  font-weight: 600;
  background: -webkit-linear-gradient(135deg, #409eff, #ff69b4);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.05);
}

.add-btn {
  padding: 10px 20px;
  font-weight: 500;
  box-shadow: 0 2px 6px rgba(64, 158, 255, 0.3);
  background: linear-gradient(135deg, #73a6ff 0%, #ff69b4 100%);
  border: none;
  transition: all 0.3s ease;
  color: white;
}

.add-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(64, 158, 255, 0.4);
}

.user-list {
  border-radius: 12px;
  border: none;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.9) 0%, rgba(240, 248, 255, 0.9) 100%);
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.06);
}

.edit-btn {
  background: linear-gradient(135deg, #d9efff 0%, #f7d9ff 100%);
  color: #5c940d;
  border: 1px solid #d3e9a6;
  transition: all 0.2s ease;
}

.edit-btn:hover {
  background: linear-gradient(135deg, #ebfbee 0%, #f7d9ff 100%);
}

.delete-btn {
  background: linear-gradient(135deg, #fff5f5 0%, #f7d9ff 100%);
  color: #e03131;
  border: 1px solid #ffc9c9;
  transition: all 0.2s ease;
}

.delete-btn:hover {
  background: linear-gradient(135deg, #ffe3e3 0%, #f7d9ff 100%);
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  padding: 10px;
  background: linear-gradient(135deg, #d9efff 0%, #f7d9ff 100%);
  border-radius: 8px;
}

:deep(.custom-dialog) {
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  background: linear-gradient(135deg, #d9efff 0%, #f7d9ff 100%);
}
</style>